package com.srwl.mytx.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.OverScroller;
import android.widget.RelativeLayout;

/**
 * Created by dahai2070 on 2018/5/14 0014.
 */

public class MyRelativeLayout extends RelativeLayout {
    private OverScroller mScroller;
    private int rightScrollBorder;
    private int leftScrollBorder;
    private int bottomScrollBorder;
    private int topScrollBorder;

    public MyRelativeLayout(Context context) {
        super(context);
        init(context);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mScroller = new OverScroller(context);
    }

    public final void smoothScrollTo(int x, int y) {
        ViewGroup parentView = (ViewGroup) getParent();
        int width = parentView.getWidth();
        int height = parentView.getHeight();
        ViewGroup.LayoutParams layoutParams = this.getLayoutParams();
//        layoutParams.width = Math.max(width, x+width-leftScrollBorder);
//        layoutParams.height =  Math.max(height, y+height-topScrollBorder);
        if (x > 0) {
            layoutParams.width = Math.max(width, x + width - leftScrollBorder);
            rightScrollBorder = x;
        } else if (x < 0) {
            layoutParams.width = Math.max(width, rightScrollBorder + width - x);
            leftScrollBorder = x;
        }
        if (y > 0) {
            layoutParams.height = Math.max(height, y + height - topScrollBorder);
            bottomScrollBorder = y;
        } else if (y < 0) {
            layoutParams.height = Math.max(height, bottomScrollBorder + height - y);
            topScrollBorder = y;
        }

        this.setLayoutParams(layoutParams);
        if (!mScroller.isFinished()) {
            return;
        }
        int scrollX = getScrollX();
        int scrollY = getScrollY();
        int deltaX = x - scrollX;
        int deltaY = y - scrollY;
        //只朝下边或者右边滑动


        if (deltaX < 0 || deltaY < 0) {
            mScroller.startScroll(scrollX, scrollY, Math.min(0, deltaX), Math.min(0, deltaY), 1000);
        }
        postInvalidate();
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            super.scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
            postInvalidate();
        }
    }
}
